/***************
 * User Summary Panel
 */
AIR2.User.Summary = function() {
    var isAdmin = (AIR2.USERINFO.type == "S");

    // MANAGER role for this user?
    // TODO this does not check org inheritance.
    var isManager = isAdmin;
    Ext.iterate(AIR2.USERAUTHZ, function(org_uuid,role,obj) {
        Ext.each(AIR2.User.ORGDATA.radix, function(uo,idx,arr) {
            if (org_uuid == uo.org_uuid && AIR2.AUTHZ.MANAGER & role) {
                isManager = true; 
            }
        });
    });

    var userPanel = new AIR2.UI.Panel({
        colspan: 2,
        title: 'User Profile',
        iconCls: 'air2-icon-user',
        items: [{
            xtype: 'air2jsdv',
            data: AIR2.User.USERDATA,
            url: AIR2.HOMEURL + '/user',
            itemSelector: '.air2-user-info',
            tpl: new Ext.XTemplate(
                '<tpl for="."><div class="air2-user-info">' +
                  '<div class="contact-info">' +
                    '{[AIR2.Format.userPhoto(values)]}' +
                    '<h2>{[AIR2.Format.userName(values)]}</h2>' +
                    '<div class="org-title">' +
                      '{[AIR2.Format.userOrgTitle(values.UserOrg[0])]} | {[AIR2.Format.userOrgLong(values.UserOrg[0])]}' +
                    '</div>' +
                    '<div class="ph-em">' +
                      '<b>e:</b>{[AIR2.Format.userEmail(values, true)]}' +
                      ' | <b>p:</b>{[AIR2.Format.userPhone(values)]}' +
                    '</div>' +
                  '</div>' +
                  '<table class="meta">' +
                    '<tr>' +
                     '<td><b>Username</b></td>' +
                     '<td>{user_username} ' +
                      '<tpl if="this.mayEdit">' +
                       ' (<a class="change-password external" target="_blank" ' +
                        'href="'+AIR2.HOMEURL+'/password">Change Password</a>)' +
                      '</tpl>' +
                     '</td>' +
                    '</tr>' +
                    '<tr>' +
                      '<td><b>Status</b></td>' +
                      '<td>{[this.formatStatus(values)]}</td>' +
                    '</tr>' +
                    '<tr>' +
                      '<td><b>Type</b></td>' +
                      '<td>{[this.formatType(values)]}</td>' +
                    '</tr>' +
                    '<tr>' +
                      '<td><b>Created by</b></td>' +
                      '<td>{[AIR2.Format.userName(values.CreUser, true)]} on {[AIR2.Format.date(values.user_cre_dtim)]}</td>' +
                    '</tr>' +
                  '</table>' +
                '</div></tpl>',
                {
                    compiled: true,
                    disableFormats: true,
                    mayEdit: AIR2.User.USERDATA.authz.may_write,
                    formatStatus: function(user) {
                        return (user.user_status == 'A') ? 'Active' : 'Inactive';
                    },
                    formatType: function(user) {
                        var t = user.user_type;
                        if (t == 'A') return 'AIR User';
                        else if (t == 'S') return 'System User';
                        else if (t == 'J') return 'Journalist User';
                        else if (t == 'R') return 'Related Journalist';
                        else return 'Unknown';
                    }
                }
            )
        },{
            xtype: 'air2jsdv',
            url: AIR2.User.USERURL + '/photo',
            data: AIR2.User.PICDATA
        },{
            xtype: 'air2jsdv',
            url: AIR2.User.USERURL + '/email',
            data: AIR2.User.UEMDATA
        },{
            xtype: 'air2jsdv',
            url: AIR2.User.USERURL + '/phone',
            data: AIR2.User.UPHDATA
        }],
        listeners: {
            beforeedit: function(form, rs) {
                var f = form.getForm();
                f.loadRecord(rs[0]); //user
                f.loadRecord(rs[1]); //photo
                f.loadRecord(rs[2]); //email

                // phone
                if (!rs[3].phantom) {
                    var s = rs[3].get('uph_number').split('-');
                    f.setValues({
                        phone1: s[0], phone2: s[1], phone3: s[2]
                    });
                }

                // load org combobox store
                var cb = form.find('name', 'home_org')[0];
                var title = form.find('name', 'uo_user_title')[0];
                cb.store.load({callback: function() {
                    var uo = rs[0].data.UserOrg;
                    if (uo.length > 0) {
                        cb.setValue(uo[0].uo_uuid);
                        title.setValue(uo[0].uo_user_title);
                    }
                }});
            },
            validate: function(form) {
                var f = form.getForm(), o = f.getValues();
                var p = '-' + o.phone1 + '-' + o.phone2 + '-' + o.phone3;
                if (o.phone1 || o.phone2 || o.phone3) {
                    if (o.phone1.length != 3 || o.phone2.length != 3 || o.phone3.length != 4) {
                        f.markInvalid({phonecomp: 'Invalid Phone Number!'});
                        return false;
                    }
                }
            },
            beforesave: function(form, rs) {
                var f = form.getForm(), o = f.getValues();
                if (!f.isValid()) return;
                f.updateRecord(rs[0]); // user

                // photo
                f.updateRecord(rs[1]);
                if (rs[1].dirty) {
                    var n = rs[1].get('uuri_value');
                    if (n.length < 1) rs[1].store.remove(rs[1]);
                }

                // email
                f.updateRecord(rs[2]);
                if (rs[2].dirty) {
                    var n = rs[2].get('uem_address');
                    if (n.length < 1) rs[2].store.remove(rs[2]);
                    else if (rs[2].phantom) rs[2].set('uem_primary_flag', true);
                }

                // phone
                if (o.phone1) {
                    var p = o.phone1 + '-' + o.phone2 + '-' + o.phone3;
                    rs[3].set('uph_number', p);
                    if (o.phone4) rs[3].set('uph_ext', o.phone4);
                    if (rs[3].phantom) {
                        rs[3].set('uph_primary_flag', true);
                        rs[3].set('uph_country', 'USA');
                    }
                }
                else {
                    rs[3].store.remove(rs[3]);
                }

                // organization/title
                var cb = form.find('name', 'home_org')[0];
                var cbr = cb.findRecord(cb.valueField, cb.getValue());
                if (cbr) {
                    cbr.beginEdit();
                    cbr.set('uo_home_flag', true);
                    f.updateRecord(cbr);
                    rs.push(cbr);
                }
            },
            aftersave: function(panel, rs) {
                Ext.getCmp('air2-app').showLocation(AIR2.Format.userName(
                    rs[0].data), 'air2-icon-source', '');

                // update uph_number and uem_address
                rs[0].data.UserEmailAddress = rs[2].data.uem_address ? [rs[2].data] : null;
                rs[0].data.UserPhoneNumber = rs[3].data.uph_number ? [rs[3].data] : null;
                if (rs[4]) {
                    rs[0].data.UserOrg = rs[4].data.uo_uuid ? [rs[4].data] : null;
                }
                userPanel.getBody().get(0).refresh();
            }
        },
        allowEdit: AIR2.User.USERDATA.authz.may_write,
        editInPlace: [{
            xtype: 'container',
            layout:'column',
            items:[{
                xtype: 'container',
                columnWidth: .5,
                layout: 'form',
                style: 'padding-right:10px',
                items: [{
                    xtype: 'fieldset',
                    title: 'User Profile',
                    defaults: {msgTarget: 'under'},
                    items: [{
                        xtype: 'air2remotetext',
                        fieldLabel: 'Login Name',
                        name: 'user_username',
                        allowBlank: false,
                        remoteUrl: AIR2.HOMEURL + '/user/name.json'
                    },{
                        xtype: 'textfield',
                        fieldLabel: 'First Name',
                        name: 'user_first_name'
                    },{
                        xtype: 'textfield',
                        fieldLabel: 'Last Name',
                        name: 'user_last_name'
                    },{
                        xtype: 'air2combo',
                        fieldLabel: 'Type',
                        name: 'user_type',
                        width: 100,
                        disabled: isAdmin ? false : true,
                        choices: [['S', 'System User'], ['A', 'AIR User']]
                    },{
                        xtype: 'air2combo',
                        fieldLabel: 'Status',
                        name: 'user_status',
                        width: 100,
                        disabled: isManager ? false : true,
                        choices: [['A', 'Active'], ['F', 'Inactive']]
                    }]
                },{
                    xtype: 'fieldset',
                    title: 'Profile Photo',
                    items: [{
                        xtype: 'textfield',
                        fieldLabel: 'Image Url',
                        name: 'uuri_value',
                        allowBlank: true,
                        vtype: 'url'
                    }]
                }]
            },{
                xtype: 'container',
                columnWidth: .5,
                layout: 'form',
                items: [{
                    xtype: 'fieldset',
                    title: 'Contact Information',
                    defaults: {msgTarget: 'under'},
                    items: [{
                        xtype: 'textfield',
                        fieldLabel: 'Email',
                        name: 'uem_address',
                        allowBlank: false,
                        vtype: 'email',
                        emptyText: 'None Provided'
                    },{
                        xtype: 'compositefield',
                        fieldLabel: 'Phone',
                        id: 'phonecomp',
                        items: [
                            {xtype: 'displayfield', value: '('},
                            {xtype: 'textfield', name: 'phone1', width: 29},
                            {xtype: 'displayfield', value: ')'},
                            {xtype: 'textfield', name: 'phone2', width: 29, margins: '0 5 0 0'},
                            {xtype: 'textfield', name: 'phone3', width: 48},
                            {xtype: 'displayfield', value: 'ext', margins: '3 5 0 5'},
                            {xtype: 'textfield', name: 'phone4', width: 29}
                        ]
                    }]
                },{
                    xtype: 'fieldset',
                    title: 'Organization Title',
                    style: 'margin:0',
                    items: [{
                        xtype: 'air2combo',
                        fieldLabel: 'Home Organization',
                        id: 'air2-user-homeorg-picker',
                        name: 'home_org',
                        store: new Ext.data.JsonStore({
                            url: AIR2.User.USERURL + '/organizations.json',
                            restful: true,
                            autoSave: false,
                            writer: new Ext.data.JsonWriter({encode: true, writeAllFields: false})
                        }),
                        valueField: 'uo_uuid',
                        displayField: 'org_display_name'
                    },{
                        xtype: 'textfield',
                        fieldLabel: 'Job Title',
                        name: 'uo_user_title',
                        emptyText: 'not set'
                    }]
                }]
            }]
        }]
    });
    return userPanel;
}
